package com.mrzhou.log.support;

import com.mrzhou.core.tool.api.CloudUser;
import com.mrzhou.core.tool.props.CloudProperties;
import com.mrzhou.core.tool.utils.DateUtil;
import com.mrzhou.core.tool.utils.Func;
import com.mrzhou.core.tool.utils.INetUtil;
import com.mrzhou.core.tool.utils.LocalDateUtil;
import com.mrzhou.log.entity.BaseLogEntity;
import com.mrzhou.web.util.WebUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author qiang.zhou
 */
public class GeneralHandlerLog {

    /**
     * 添加在保存在请求体中的请求信息
     * @param baseLogEntity
     */
    public static void addRequestToLog(BaseLogEntity baseLogEntity) {
        HttpServletRequest request = WebUtil.getRequest();
        CloudUser user = WebUtil.getUser();
        if(null != user) {
            baseLogEntity.setTenantId(StringUtils.isNotBlank(user.getTenantId()) ? user.getTenantId() : "000000");
            baseLogEntity.setCreateBy(user.getAccount());
        }
        baseLogEntity.setMethod(request.getMethod());
        baseLogEntity.setUserAgent(request.getHeader(WebUtil.USER_AGENT_HEADER));
        baseLogEntity.setRequestUri(WebUtil.getPath(request.getRequestURI()));
        baseLogEntity.setRemoteIp(WebUtil.getIp(request));
        // 添加链路id
        baseLogEntity.setCloudId(WebUtil.getCloudId());
        // 调用者， 可能为空
        baseLogEntity.setCreateBy(Func.toStr(WebUtil.getUserId()));
        baseLogEntity.setCreateTime(LocalDateUtil.nowTime());
    }

    /**
     *  添加其他的信息, 这里只添加一些系统级别的消息，
     *  防止在使用移除监听时无法在获取{@link HttpServletRequest}, 因为不在同一个线程中
     */
    public static void addOtherToLog(CloudProperties cloudProperties, BaseLogEntity log) {
        // 当前环境
        log.setEnv(cloudProperties.getEnv());
        // 服务名称， 也是注册在nacos中的serviceId
        log.setServerId(cloudProperties.getApplicationName());
        // 服务器名称
        log.setServerHost(INetUtil.getOsHostName());
        // 服务器IP
        log.setServerIp(INetUtil.getOsHost());
    }

}
